package com.hxzy.servlet;

import com.hxzy.bean.Message;
import com.hxzy.bean.User;
import com.hxzy.service.Impl.MessageServiceImpl;
import com.hxzy.service.MessageService;
import com.hxzy.util.CommonUtil;
import com.hxzy.vo.JsonResult;
import com.hxzy.vo.StatusCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

@WebServlet("/publishMessage")
public class MessageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1设置编码方式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        JsonResult result=new JsonResult();//声明放回Client的端
        String share = req.getParameter("share");
        //2如果share的值为null
        if (Objects.isNull(share)){
            result.setCode(StatusCode.EXCEPTION.getCode());
            result.setMessage(StatusCode.EXCEPTION.getMessage());
            CommonUtil.back(resp,result);
            return;
        }

        //3验证用户是否登录就访问
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if (Objects.isNull(user)){//如果user为null则没有登录
            result.setCode(StatusCode.NOT_LOGIN.getCode());
            result.setMessage(StatusCode.NOT_LOGIN.getMessage());
            CommonUtil.back(resp,result);
            return;
        }

        //成功就返回一个成功的状态码------------------我的分析不到位
            /**
             * 1创建一个message的对象
             * 2添加到数据库
             * 3判断成功和失败返回相应的状态码
             */
        Message message=new Message();
        message.setContent(share);//设置内容
        message.setMesDate(LocalDateTime.now());//设置时间
        message.setUser((User) user);//设置user对象
        MessageService service=new MessageServiceImpl();
        int save = service.save(message);
        if (save>0){//成功
            result.setCode(StatusCode.SUCCESS.getCode());
            result.setMessage(StatusCode.SUCCESS.getMessage());
        }else {//失败
            result.setData(StatusCode.SYS_ERROR.getCode());
            result.setMessage(StatusCode.SYS_ERROR.getMessage());
        }
        CommonUtil.back(resp,result);
    }
}
